package org.gthelper.handler;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.gthelper.data.DataGeter;
import org.gthelper.database.UserInfo;
import org.gthelper.error.ErrorCode;
import org.gthelper.order.OrderInfo;
import org.gthelper.security.IchkID;
import org.gthelper.security.ValidationRSA;

/**
 * 检验ID是否存在，存在则返回错误码，不存在，则接纳注册并返回加密用的公钥
 * @author pig
 */
public class PreReg extends Handler
{

	@Override
	public int handle(OrderInfo orderinfo) {
		// TODO 自动生成的方法存根
		//get id
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataGeter dg = new DataGeter();
		int errcode=dg.getData(orderinfo.orderStream, baos);
		if(errcode!=ErrorCode.NORMAL)return errcode;
		try {
			String usrid=new String(baos.toByteArray(),"UTF-8");
			
			try {
				if(UserInfo.idIsExist(usrid))return ErrorCode.IDEXIST;
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				return ErrorCode.DATABASEERR;
			}
			
			if(!nameOK(usrid))return ErrorCode.WRONGID;
			
			//生成密钥
			IchkID chkid = new ValidationRSA();
			Map<String,Object>keyMap = chkid.initKey();
			byte[] pubkey = chkid.getPublicKey(keyMap);
			byte[] prikey = chkid.getPrivateKey(keyMap);
			
			if(!UserInfo.insertNewUser(usrid, IchkID.encryptBASE64(prikey)))return ErrorCode.DATABASEERR;

			//返回公钥
			DataOutputStream dos = new DataOutputStream(orderinfo.mainOutput);
			dos.writeLong((long)(pubkey.length));
			dos.write(pubkey);
			
			return ErrorCode.NORMAL;
				
			
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return ErrorCode.UNKNOWN;
		}
		return ErrorCode.NORMAL;
	}
	
	/**
	 * 检查用户名是否合法
	 * @param usrid
	 * @return
	 */
	private boolean nameOK(String usrid) {
		// TODO 自动生成的方法存根
		if(usrid.length()>20)return false;
		for(int i=0;i<usrid.length();i++)
		{
			char tmp = usrid.charAt(i);
			if(((tmp<'a')||(tmp>'z'))&&((tmp<'1')||(tmp>'9'))&&(tmp!='0')&&(tmp!='_'))return false;
		}
		return true;
	}

	
}